import 'package:flutter/material.dart';
import 'preview_article.dart';
import '../../services/database_helper.dart';

class WordPage extends StatefulWidget {
  const WordPage({super.key});

  @override
  State<WordPage> createState() => _WordPageState();
}

class _WordPageState extends State<WordPage> {
  final List<String> _tabs = ['全部', '一星', '二星', '三星', '四星', '五星'];
  int _selectedIndex = 0;
  List<Map<String, dynamic>> _articles = [];
  bool _isLoading = true;

  final List<Color> _bookColors = [
    const Color(0xFF8B7BF7),
    const Color(0xFF4CD964),
    const Color(0xFFFF3B30),
    const Color(0xFF5856D6),
    const Color(0xFF007AFF),
    const Color(0xFFFF9500),
    const Color(0xFF4A90E2),
    const Color(0xFFFFCC00),
  ];

  @override
  void initState() {
    super.initState();
    _initDatabase();
  }

  Future<void> _initDatabase() async {
    try {
      await DatabaseHelper.init();
      await _loadArticles();
    } catch (e) {
      print('Failed to initialize database: $e');
    }
  }

  Future<void> _loadArticles() async {
    setState(() => _isLoading = true);
    
    try {
      final articles = await DatabaseHelper.getArticles(
        difficulty: _selectedIndex > 0 ? _selectedIndex : null
      );

      setState(() {
        _articles = articles;
        _isLoading = false;
      });
    } catch (e) {
      print('Error loading articles: $e');
      print('Stack trace: ${StackTrace.current}');
      setState(() => _isLoading = false);
    }
  }

  @override
  void dispose() {
    DatabaseHelper.close();
    super.dispose();
  }

  Color _getRandomColor() {
    return _bookColors[DateTime.now().microsecond % _bookColors.length];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          // 顶部蓝色背景
          Container(
            color: const Color(0xFF4B6BFB),
            child: SafeArea(
              bottom: false,
              child: Container(
                height: 56,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  children: [
                    IconButton(
                      onPressed: () => Navigator.pop(context),
                      icon: const Icon(
                        Icons.arrow_back_ios,
                        color: Colors.white,
                        size: 20,
                      ),
                    ),
                    const Text(
                      '文章列表',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),

          // 标签栏
          Container(
            color: const Color(0xFF4B6BFB),
            padding: const EdgeInsets.only(bottom: 16),
            child: SizedBox(
              height: 36,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                itemCount: _tabs.length,
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.only(right: 12),
                    child: _buildTab(index),
                  );
                },
              ),
            ),
          ),

          // 文章列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : ListView.builder(
                    padding: const EdgeInsets.all(16),
                    itemCount: _articles.length,
                    itemBuilder: (context, index) {
                      final article = _articles[index];
                      return _buildBookItem(
                        title: article['title'] ?? '',
                        subtitle: '难度：${article['difficulty']}星 ',
                        count: '来源：${article['source']}',
                        article: article,
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildTab(int index) {
    final isSelected = _selectedIndex == index;
    return GestureDetector(
      onTap: () {
        setState(() => _selectedIndex = index);
        _loadArticles();
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? Colors.white : Colors.white.withAlpha(26),
          borderRadius: BorderRadius.circular(20),
        ),
        child: Text(
          _tabs[index],
          style: TextStyle(
            color: isSelected ? const Color(0xFF4B6BFB) : Colors.white,
            fontSize: 13,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget _buildBookItem({
    required String title,
    required String subtitle,
    required String count,
    required Map<String, dynamic> article,
    Color? color,
  }) {
    final itemColor = color ?? _getRandomColor();
    
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 2, vertical: 1),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha(13),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Material(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => PreviewArticlePage(
                  articleId: article['id'],
                ),
              ),
            );
          },
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: itemColor.withAlpha(26),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Icon(
                        Icons.book,
                        color: itemColor,
                        size: 16,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        title,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),                    
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  subtitle,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                    height: 1.5,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  count,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[400],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}